import type { InputProps } from 'antd';
import { Input } from 'antd';
import type { ChangeEvent, FocusEvent } from 'react';
import { useState } from 'react';

const { TextArea } = Input;

type Props = InputProps & {
  onChange?: (value: string) => void;
};

const EnhancedTextArea: React.FC<Props> = ({ value, onChange, ...rest }) => {
  const [data, setData] = useState('');

  const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
    if (onChange) {
      onChange(e.target.value);
    }
  };

  const handleBlur = (e: FocusEvent<HTMLTextAreaElement>) => {
    const ret = e.target.value.replaceAll('\\xc2\\xa', ' ').trim();
    setData(ret);
    if (onChange) {
      onChange(ret);
    }
  };

  return (
    <TextArea
      value={value !== undefined ? value : data}
      onChange={handleChange}
      onBlur={handleBlur}
      {...rest}
    />
  );
};

export default EnhancedTextArea;
